/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: PayApiRestTemplateServiceImpl
 * Author:   wh
 * Date:     2019/5/15 12:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.itcs.eureka.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcs.eureka.exception.TranBusException;
import com.itcs.eureka.service.PayApiFeignClientService;
import com.itcs.eureka.service.PayApiRestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: ITCS_CLOUD
 * @ClassName: PayApiRestTemplateServiceImpl
 * @Description: RestTemplate请求模板
 * @author: wanghui
 * @date: 2019/5/15 12:02
 * @Version: 1.0.0
 */
@Slf4j
@Service("payApiRest")
public class PayApiRestTemplateServiceImpl implements PayApiFeignClientService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String getTrancode() {
        return null;
    }

    @Override
    public Map<String, Object> exchange(String serverId, String trancode, Map<String, Object> reqData) {
        log.info("接收Eureka请求:{} --- {}[{}]", serverId, trancode, JSON.toJSONString(reqData));
        Map<String, Object> res = null;
        try {
            Map<String, Object> reqRecord = new HashMap<>();
            reqRecord.put("req_msg", JSON.toJSONString(reqData));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(reqRecord), headers);
            String uri = "http://{serviceId}/{trancode}";
            res = restTemplate.exchange(uri, HttpMethod.POST, entity,
                    new ParameterizedTypeReference<Map<String, Object>>(){},
                    serverId,trancode).getBody();
        } catch (TranBusException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(trancode + ",请求调用失败:" + e.getMessage(), e);
            throw new TranBusException("999999", trancode + ",请求调用失败:" + e.getMessage());
        }
        return res;
    }
}
